<!DOCTYPE html>
<html dir="ltr">

<head>
  <meta charset="UTF-8">
  <title>Refresher</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <link href="../../../../../css/ionic.bundle.css" rel="stylesheet">
  <link href="../../../../../scripts/testing/styles.css" rel="stylesheet">
  <script src="../../../../../scripts/testing/scripts.js"></script>
  <script src="../../../../../dist/ionic.js"></script>
</head>

<body>
  <ion-app>
    <ion-header translucent>
      <ion-toolbar>
        <ion-title>Pull To Refresh</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content fullscreen>
      <ion-refresher id="refresher" slot="fixed">
        <ion-refresher-content pulling-text="Pull to refresh..." refreshing-spinner="bubbles" refreshing-text="Refreshing...">
        </ion-refresher-content>
      </ion-refresher>

      <ion-list id="list"></ion-list>
    </ion-content>
  </ion-app>

  <script type="text/javascript" src="preview/data.js"></script>
  <script>
    const disableButton = document.getElementById('disableButton');
    const list = document.getElementById('list');
    const refresher = document.getElementById('refresher');

    refresher.addEventListener('ionRefresh', async function () {
      console.log('Loading data...');
      const data = await getAsyncData();
      users = data.concat(users);

      if (users.length == json.length) {
        console.log("All data has been loaded");
        refresher.disabled = true;
      }

      refresher.complete();
      render();
      console.log('Done');
    });

    function toggleDisableRefresher() {
      refresher.disabled = !refresher.disabled;
      disableButton.innerHTML = refresher.disabled ? 'Enable' : 'Disable';
    }

    let users = [];

    for (var i = 0; i < 4; i++) {
      users.push(json[i]);
    }

    function render() {
      let html = '';
      for (let user of users) {
        html += `
          <ion-item>
            <ion-avatar slot="start">
              <img src="${user.img}"/>
            </ion-avatar>
            <ion-label>
              <h2>${user.name}</h2>
              <p>${user.description}</p>
            </ion-label>
          </ion-item>
        `;
      }
      list.innerHTML = html;
    }

    function getAsyncData() {
      // async return mock data
      return new Promise(resolve => {
        setTimeout(() => {
          length = users.length;
          let data = [];
          for (var i = length; i < length + 2; i++) {
            data.push(json[i]);
          }
          resolve(data);
        }, 500);
      });
    }

    render();
  </script>
</body>

</html>
